package com.labichaoka.chaoka.utils;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;

import java.lang.reflect.Type;

/**
 * Created by jackwang on 16-9-30.
 */

public class WrappedGson {
    private final ExclusionStrategy mSerialExclusion = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    };
    private final Gson mGson;
    private final ExclusionStrategy mDeserialExclusion = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            Expose expose = f.getAnnotation(Expose.class);
            return expose != null && !expose.deserialize();
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };

    private static final class Holder {
        private static final WrappedGson sInst = new WrappedGson();
    }

    public static WrappedGson getInstance() {
        return Holder.sInst;
    }

    private WrappedGson() {
        mGson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .addSerializationExclusionStrategy(mSerialExclusion)
                .addDeserializationExclusionStrategy(mDeserialExclusion)
                .create();
    }

    public String toJson(Object jsonObj) {
        return mGson.toJson(jsonObj);
    }

    public <T> T fromJson(String jsonStr, Class<T> type) {
        if (type == null)
            throw new IllegalArgumentException("type is null!");

        return mGson.fromJson(jsonStr, type);
    }
    public <T> T fromJson(String jsonStr, Type type) {
        if (type == null)
            throw new IllegalArgumentException("type is null!");

        return (T) mGson.fromJson(jsonStr, type);
    }

}
